package com.jumper.study.front.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jumper.study.common.api.CommonResult;
import com.jumper.study.common.api.ResultCode;
import com.jumper.study.common.util.CaptchaUtil;
import com.jumper.study.common.util.RequestUtil;
import com.jumper.study.front.dto.req.RegisterReq;
import com.jumper.study.front.service.StudentService;

import jakarta.servlet.http.HttpServletRequest;

@RestController("frontRegisterController")
@RequestMapping("/api/auth")
public class RegisterController {
    
    @Autowired
    private StudentService studentService;

    @Autowired
    private CaptchaUtil captchaUtil;

    /**
     * 学员注册 
     * @param req
     * @return
     */
    @PostMapping("/register")
    public CommonResult<Boolean> index(HttpServletRequest request, @RequestBody @Validated RegisterReq req) {
        if (!captchaUtil.verify(req.getCode(), RequestUtil.getIp(request))) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED.getCode(), "验证码错误");
        }
        if (studentService.usernameExist(req.getUsername())) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED.getCode(), "用户名已存在");
        }
        req.setIp(RequestUtil.getIp(request));
        req.setAgent(RequestUtil.getAgent(request));
        boolean result = studentService.register(req);
        return CommonResult.success(result);
    }
}
